package cn.xy.base.server.utils;

import cn.hutool.json.JSONUtil;
import cn.xy.commons.annotation.ApiAuth;
import cn.xy.commons.core.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.ServletResponse;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 *  @author xy
 */
@Slf4j
public class WebContextUtil {

    private WebContextUtil() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * 检查某个接口是否忽略登陆
     *
     * @param handler handler
     * @return 是否忽略登陆
     */
    public static boolean checkIgnore(Object handler) {
        if (handler == null) {
            return false;
        }
        boolean ignoreAuth;
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        ApiAuth classAuth = handlerMethod.getMethod().getDeclaringClass().getAnnotation(ApiAuth.class);
        ignoreAuth = classAuth != null && classAuth.ignore();
        ApiAuth methodAuth = handlerMethod.getMethodAnnotation(ApiAuth.class);
        if (methodAuth != null) {
            //优先方法注解
            ignoreAuth = methodAuth.ignore();
        }
        return ignoreAuth;
    }

    public static void setResponse(ServletResponse response, Result<String> result) {
        try {
            OutputStream os = response.getOutputStream();
            String jsonStr = JSONUtil.toJsonStr(result);
            os.write(jsonStr.getBytes(StandardCharsets.UTF_8));
            response.setContentType("application/json;charset=UTF-8");
        } catch (Exception ex) {
            log.warn("exception=" + ex);
        }
    }

    public static void setResponse(ServletResponse response, int code, String msg) {
        Result<String> result = Result.error(code, msg);
        WebContextUtil.setResponse(response, result);
    }
}
